<template>
    <div class="positionSetting">
        <div class="tableContent">
            <div class="filtrate">
                <el-form :inline="true" ref="form" :model="form" label-width="auto" size="mini">
                    <el-form-item label="分组名称">
                        <el-input v-model="form.name" placeholder="请输入"></el-input>
                    </el-form-item>
                </el-form>
                <div class="button">
                    <el-button type="primary" icon="el-icon-search" @click="query" size="small">查询</el-button>
                    <el-button icon="el-icon-refresh-left" size="small" @click="tableRefresh">重置</el-button>
                    <el-button type="primary" icon="el-icon-plus" size="small" @click="addGroupForm">新增</el-button>
                </div>
            </div>
            <el-table
                :data="tableData"
                style="font-size: 13px;margin-top: 10px;"
                :header-cell-style="tableHeader"
                id="groupTable">
                <el-table-column
                prop="groupName"
                label="组别名称"
                :show-overflow-tooltip="true"
                width="120">
                </el-table-column>
                <el-table-column
                prop="groupLevel"
                label="组别等级"
                width="90">
                </el-table-column>
                <el-table-column
                prop="belongOperatorNameList"
                label="管辖操作员"
                :show-overflow-tooltip="true"
                width="120">
                </el-table-column>
                <el-table-column
                prop="groupDesc"
                label="组别描述"
                :show-overflow-tooltip="true"
                width="100">
                </el-table-column>
                <el-table-column
                prop="memberCount"
                label="成员数量"
                width="90">
                </el-table-column>
                <el-table-column
                prop="createDate"
                label="创建时间"
                width="155">
                </el-table-column>
                <el-table-column
                prop="modifyDate"
                label="最新修改时间"
                width="155">
                </el-table-column>
                <el-table-column
                prop="modifyOperatorName"
                label="最新修改人"
                width="120">
                </el-table-column>
                <el-table-column label="操作" width="230">
                    <template slot-scope="scope" v-if="scope.row.parentId != 99||scope.row.groupLevel != 1">
                        <span
                        size="mini"
                        class="tableOperate"
                        @click="handleBaseEdit(scope.$index, scope.row)">修改基本信息</span>
                        <span
                        size="mini"
                        class="tableOperate"
                        @click="handlePersonEdit(scope.$index, scope.row)">修改分组人员</span>
                        <span
                        size="mini"
                        type="danger"
                        class="tableOperate"
                        @click="handleDelete(scope.$index, scope.row)">删除</span>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page.sync="currentPage1"
                :page-size="limit"
                layout="total, prev, pager, next"
                :total="total">
            </el-pagination>
        </div>
        <!-- 分组新增 -->
        <el-dialog
        :title="dialogName"
        :visible.sync="showAddForm"
        append-to-body
        width="30%"
        :before-close="handleClose">
        <el-form :model="addForm" :rules="rules" ref="addForm" size="small" label-position="left">
            <el-form-item label="分组名称" :label-width="formLabelWidth" prop="name">
                <el-input v-model="addForm.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="分组描述" :label-width="formLabelWidth" prop="detail">
                <el-input type="textarea" v-model="addForm.detail"></el-input>
            </el-form-item>
            <div>
                <div>父级分组</div>
                <div class="groupChoose">
                    <el-tree
                        :data="groupList"
                        show-checkbox
                        node-key="groupId"
                        check-strictly="true"
                        ref="groupList"
                        :default-checked-keys="changeParentId"
                        :props="defaultProps">
                    </el-tree>
                </div>
            </div>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="showAddForm = false">取消</el-button>
            <el-button type="primary" @click="addGroup('addForm')" v-if="dialogName == '分组新增'">下一步</el-button>
            <el-button type="primary" @click="groupChange('addForm')" v-else>确定</el-button>
        </span>
        </el-dialog>
        <!-- 分组修改 -->
        <el-dialog
        :visible.sync="showAddList"
        append-to-body
        width="623px"
        :before-close="handleClose">
           <el-transfer
                filterable
                :filter-method="filterMethod"
                filter-placeholder="请输入人员名称"
                v-model="choosePersonIds"
                :titles="['可选人员', '已选人员']"
                :props="{
                    key: 'personId',
                    label: 'personName'
                }"
                :data="personList">
            </el-transfer>
        <span slot="footer" class="dialog-footer">
            <el-button @click="toAddForm" v-if="dialogName == '分组新增'">上一步</el-button>
            <el-button @click="showAddList = false" v-else>取消</el-button>
            <el-button type="primary" @click="confirmGroup()">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>


<script>

export default {
    components: {  },
    props: {

    },
    data(){
        return {
            value: [],
            tableData: [],
            timer: '',
            tableHeader: {
                backgroundColor: '#E1F1FF',
                color: '#4389D6'
            },
            form: {
                name: '',
            },
            addForm: {
                name: '',
                detail: ''
            },
            changeForm: {
                name: '',
                detail: ''
            },
            rules: {
                name: [
                    {
                        required: true, 
                        validator: (rule, value, callback) => {
                            if (value == '') {
                                callback(new Error('请填分组名称'))
                            } else if (value.indexOf(" ") != -1) {
                                callback(new Error('禁止填写空格'))
                            } else {
                                callback()
                            }
                        },
                        trigger: 'change' 
                    }
                ],
                detail: [
                    { required: true, message: '请填写分组描述', trigger: 'blur' }
                ]
            },
            showAddForm: false,
            showAddList: false,
            checkedCities: [],
            cities: [],
            groupList: [],
            defaultProps: {
                children: 'childGroupList',
                label: 'groupName'
            },
            currentPage1: 1,
            limit: '',
            page: 1,
            total: 0,
            groupName: '',
            groupNameNew: '',//新建分组名称
            groupDescNew: '',//新建分组描述
            groupLevelNew: '',//新建分组组别等级
            parentIdNew: '',//新建分组父级组别编码
            personIds: '',//关联被定位人员编码
            personList: [],
            choosePersonIds: [],//分组选中人员的id
            changeGroupId: '',//点击修改的groupId
            changeParentId: [],//点击修改的父级分组
            dialogName: '',//弹框标题
            changeIndex: ''//修改数组数据的index
        };
    },
    methods:{
        //表格删除某一行
        handleDelete(i,item) {
            this.$confirm("确定删除这条数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
            .then(() => {
                let url = '/lbs/usercenter/group/deleteGroupInfo';
                let params = {
                    groupId: item.groupId
                }
                this.$http.post(url, params).then(res => {
                    let {retCode,retMsg,data} = res.data;
                    if (retCode == '0') {//成功的情况
                        this.$message({
                            type: "success",
                            message: "删除成功!",
                        });
                        this.qryGroupList();
                    } else {
                      this.$alert(retMsg || '请求失败');
                    }
                }).catch(err => {
                  this.$alert(err)
                })
                })
                .catch(() => {
                this.$message({
                    type: "info",
                    message: "已取消删除",
                });
            });
        },
        //表格查询
        query() {
            this.qryGroupList();
        },
        //表格重置
        tableRefresh() {
            this.form = {};
        },
        handleCurrentChange(val) {
            this.page = val;
            if(this.tableData.length == 0) {
                return
            }
            this.qryGroupList();
        },
        //分组添加
        addGroup(formName) {
            let self = this;
            self.$refs[formName].validate((valid) => {
                if (valid) {
                    let mes = self.$refs.groupList.getCheckedNodes()[0];
                    if(self.$refs.groupList.getCheckedNodes().length == 0) {
                        self.parentIdNew = '-1';
                        self.groupLevelNew = '1';
                    }else if(self.$refs.groupList.getCheckedNodes().length > 1) {
                        self.$message({
                            message: "只能选择一个父级分组",
                            type: 'error'
                        });
                        return
                    }else if(self.$refs.groupList.getCheckedNodes().length == 1){
                        self.showAddForm = false;
                        self.showAddList = true;
                        self.parentIdNew = mes.groupId;
                        self.groupLevelNew = parseInt(mes.groupLevel) + 1;
                    }
                    self.groupNameNew = self.addForm.name;
                    self.groupDescNew = self.addForm.detail;
                    //判断分组名称是否已存在
                    let url = "/lbs/usercenter/group/judgeGroupNameRepeat";
                    let params = {
                        groupName: self.groupNameNew
                    }
                    self.$http.post(url,params).then(res => {
                        console.log(params);
                        console.log(res);
                        let {retCode,retMsg,data} = res.data;
                        if (retCode == '0') {//成功的情况
                            if(data == '1') {
                                self.$message({
                                    message: "分组名称已存在",
                                    type: 'error'
                                });
                                return
                            }
                            self.qryChooseAbledMember();
                            self.qryChoosedMember();
                            self.showAddList = true;
                            self.showAddForm = false;
                        }
                    }).catch(err => {
                        this.$alert(err)
                    })
                } else {
                    return false;
                }

            });
        },
        handleChange(value, direction, movedKeys) {
            console.log(value, direction, movedKeys);
        },
        //新增分组
        confirmGroup() {
            if(this.dialogName == '分组新增') {
                let url = "/lbs/usercenter/group/createGroupInfo"
                let params = {
                    groupName: this.groupNameNew,
                    groupDesc: this.groupDescNew,
                    groupLevel: this.groupLevelNew,
                    parentId: this.parentIdNew,
                    personIds: JSON.stringify(this.choosePersonIds)
                }
                this.$http.post(url, params).then(res => {
                    let {retCode,retMsg,data} = res.data;
                    if (retCode == '0') {//成功的情况
                        this.$message({
                            message: "添加成功",
                            type: 'success'
                        });
                        this.qryEcFirstSecondGroupInfo();
                        this.qryGroupList();
                        this.showAddList = false;
                        this.showAddForm = false;
                    } else {
                        this.$message({
                            message: retMsg || 请求错误,
                            type: 'error'
                        });
                    }
                }).catch(err => {
                this.$alert(err)
                })
            }else {
                let url = '/lbs/usercenter/group/updateGroupPersonRel';
                let params = {
                    groupId: this.changeGroupId,
                    personIds: JSON.stringify(this.choosePersonIds),
                }
                this.$http.post(url, params).then(res => {
                    let {retCode,retMsg,data} = res.data;
                    if (retCode == '0') {//成功的情况
                        this.$message({
                            message: retMsg,
                            type: 'success'
                        });
                        this.showAddList = false;
                        this.qryGroupList();
                    } else {
                        this.$message({
                            message: retMsg || 请求错误,
                            type: 'error'
                        });
                    }
                }).catch(err => {
                    this.$alert(err)
                })
            }
        },
        //获取分组列表
        qryEcFirstSecondGroupInfo() {
            let url = '/lbs/usercenter/group/qryEcFirstSecondGroupInfo';
            let params = {
                groupId: this.changeGroupId
            }
            this.$http.post(url, params).then(res => {
                let {retCode,retMsg,data} = res.data;
                if (retCode == '0') {//成功的情况
                    this.groupList = data;
                    for(let i=0;i<this.groupList.length;i++) {
                        if(this.groupList[i].groupId == this.changeGroupId) {
                            let mes = this.groupList[i];
                            mes.disabled = true;
                            this.$set(this.groupList, i, mes);
                        }
                        for(let j=0;j<this.groupList[i].childGroupList.length;j++) {
                            if(this.groupList[i].childGroupList[j].groupId == this.changeGroupId) {
                                let mes = this.groupList[i];
                                mes.childGroupList[j].disabled = true;
                                console.log(this.groupList[i].childGroupList[j]);
                                this.$set(this.groupList, i, mes);
                            }
                        }
                    }
                  this.findParentId(this.groupList);
                } else {
                    this.$message({
                        message: retMsg || 请求错误,
                        type: 'error'
                    });
                }
            }).catch(err => {
              this.$alert(err)
            })
        },
        //查询分组信息列表
        qryGroupList() {
            let url = '/lbs/usercenter/group/qryGroupInfoList';
            let params = {
                groupName: this.groupName,
                pageSize: this.limit,
                pageNum: this.page,
                groupName: this.form.name
            }
            this.$http.post(url, params).then(res => {
                let {retCode,retMsg,pageData, total} = res.data;
                if (retCode == '0') {//成功的情况
                  this.tableData = pageData;
                  this.tableData.forEach(items => {
                      items.belongOperatorNameList.join(',');
                      items.groupLevel = items.groupLevel + '级';
                  })
                  this.total = total;
                } else {
                    this.$message({
                        message: retMsg || 请求错误,
                        type: 'error'
                    });
                }
            }).catch(err => {
              this.$alert(err)
            })
        },
        //分组新增上一步
        toAddForm() {
            this.showAddForm = true;
            this.showAddList = false;
        },
        //分组新增
        addGroupForm() {
            this.groupLevelNew = "";
            this.parentIdNew = "";
            this.choosePersonIds = [];
            this.changeGroupId = "";
            this.showAddForm = true;
            this.dialogName = "分组新增";
            this.changeParentId = [];
            this.$nextTick(() => {
                this.$refs['addForm'].resetFields();
                this.$refs.groupList.setCheckedKeys([]);
            })
            this.qryEcFirstSecondGroupInfo();
        },
        //分组修改确定按钮
        groupChange() {
            let mes = this.$refs.groupList.getCheckedNodes()[0];
            if(this.$refs.groupList.getCheckedNodes().length == 0) {
                this.parentIdNew = '-1';
                this.groupLevelNew = '1';
            }else if(this.$refs.groupList.getCheckedNodes().length > 1) {
                this.$message({
                    message: "只能选择一个父级分组",
                    type: 'error'
                });
                return
            }else if(this.$refs.groupList.getCheckedNodes().length == 1){
                this.parentIdNew = mes.groupId;
                this.groupLevelNew = parseInt(mes.groupLevel) + 1;
            }
            //判断分组名称是否已存在
            let urls = "/lbs/usercenter/group/judgeGroupNameRepeat";
            let params = {
                groupName: this.addForm.name,
                groupId: this.changeGroupId
            }
            this.$http.post(urls,params).then(res => {
                let {retCode,retMsg,data} = res.data;
                if (retCode == '0') {//成功的情况
                    if(data == '1') {
                        this.$message({
                            message: "分组名称已存在",
                            type: 'error'
                        });
                        return
                    }else {
                        this.groupNameNew = this.addForm.name;
                        this.groupDescNew = this.addForm.detail;
                        let url = '/lbs/usercenter/group/updateGroupInfo';
                        let param = {
                            groupId: this.changeGroupId,
                            parentId: this.parentIdNew,
                            groupName: this.groupNameNew,
                            groupLevel: this.groupLevelNew,
                            groupDesc: this.groupDescNew
                        }
                        this.$http.post(url, param).then(res => {
                            let {retCode,retMsg,data} = res.data;
                            if (retCode == '0') {//成功的情况
                                this.$message({
                                    message: retMsg,
                                    type: 'success'
                                });
                                this.qryGroupList();
                                this.showAddForm = false;
                            } else {
                                this.$message({
                                    message: retMsg,
                                    type: 'error'
                                });
                            }
                        }).catch(err => {
                            this.$alert(err)
                        })
                    }
                }
            }).catch(err => {
                this.$alert(err)
            })
        },
        //分组基本信息修改
        handleBaseEdit(index, mes) {
            this.changeIndex = index;
            this.dialogName = "分组修改";
            this.changeParentId = [];
            this.showAddForm = true;
            this.addForm.name = mes.groupName;
            this.addForm.detail = mes.groupDesc;
            this.changeGroupId = mes.groupId;
            this.qryEcFirstSecondGroupInfo();
        },
        //分组成员修改
        handlePersonEdit(index, mes) {
            console.log(mes);
            this.changeIndex = index;
            this.dialogName = "分组修改";
            this.changeGroupId = mes.groupId;
            this.showAddList = true;
            this.qryChooseAbledMember();
            this.qryChoosedMember();
        },
        //获取已关联人员id
        qryChoosedMember(index, mes) {
            let url = "/lbs/usercenter/group/qryChoosedMember";
            let params = {
                groupId: this.changeGroupId
            }
            this.$http.post(url, params).then(res => {
                let {retCode,retMsg,data} = res.data;
                if (retCode == '0') {//成功的情况
                    this.choosePersonIds = data.map(items => {
                        return items.personId
                    })
                } else {
                    this.$message({
                        message: retMsg || 请求错误,
                        type: 'error'
                    });
                }
            }).catch(err => {
              this.$alert(err)
            })
        },
        //获取可关联人员列表
        qryChooseAbledMember() {
            let url = "/lbs/usercenter/group/qryChooseAbledMember";
            this.$http.post(url).then(res => {
                let {retCode,retMsg,data} = res.data;
                if (retCode == '0') {//成功的情况
                    this.personList = data;
                } else {
                    this.$alert(retMsg || '请求失败');
                }
            }).catch(err => {
                this.$alert(err)
            })
        },
        //查找当前组父级分组
        findParentId(list) {
            console.log(list);
            list.forEach(items => {
                if(items.isSelected == '1') {
                    this.changeParentId.push(items.groupId)
                }
                items.childGroupList.forEach(item => {
                    if(item.isSelected == '1') {
                        this.changeParentId.push(item.groupId)
                    }
                })
            })
        }
    },
    created() {
        
    },
    mounted() {
        this.limit = parseInt((document.getElementById('groupTable').clientHeight-48)/48);
        this.qryGroupList();
    }
}
</script>

<style scoped lang="less">
.positionSetting {
    display: flex;
}
.tableContent {
    border-left: 1px solid #EEEEEE;
    display: flex;
    flex-direction: column;
}
.filtrate {
    height: 62px;
    background: #FBFBFB;
    border-bottom: 1px solid #E1E1E1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    border-radius: 0 16px 0 0;
}
.groupChoose {
    width: 100%;
    height: 200px;
    margin-top: 5px;
    margin-left: 20px;
}
</style>
<style lang="less">
.positionSetting {
    .el-button+.el-button {
        margin: 0;
    }
    .el-table {
        margin: 0 20px;
        width: auto;
        overflow-y: scroll;
    }
    .el-pagination {
        text-align: center;
    }
    .el-form--inline .el-form-item {
        margin-bottom: 0;
        margin-right: 0;
    }
    .el-input__inner {
        height: 32px;
    }
    .el-pagination {
        margin: 10px 0;
    }
    .el-form-item__label-wrap .el-form-item__label {
        font-size: 13px;
    }
    .el-table .cell {
        display: flex;
        justify-content: space-between;
    }
    .tableOperate {
        color: #3484E5;
        cursor: pointer;
    }
    .el-button--small {
        padding: 9px 6px;
    }
    .el-transfer-panel__body {
        width: 300px;
    }
}
.groupChoose .el-checkbox-group {
        display: flex;
        flex-direction: column;
        height: 100%;
        overflow-y: scroll;
        label {
            margin-top: 11px;
        }
    }
</style>



